package com.example.logindb.controller;

import com.example.logindb.dto.UserDTO;
import com.example.logindb.entity.*;
import com.example.logindb.sevices.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.security.Principal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
public class AdminController {

    private HelpService helpService;
    private UserService userService;
    private RouteService routeService;
    private RelationService relationService;
    private OnlineService onlineService;
    private LocationService locationService;
    private FeedbackService feedbackService;
    @Autowired
    public AdminController(UserService userService, RouteService routeService, RelationService relationService, OnlineService onlineService, LocationService locationService, HelpService helpService, FeedbackService feedbackService) {
        this.userService = userService;
        this.routeService = routeService;
        this.relationService = relationService;
        this.onlineService = onlineService;
        this.locationService = locationService;
        this.helpService = helpService;
        this.feedbackService = feedbackService;
    }

    @GetMapping("/dashboard")
    public String adminHome(Principal principal,Model model) {

        List<UserDTO> users = userService.findAllByRole("USER");
        User user =userService.findByUsername(principal.getName());

        model.addAttribute("users", users);
        model.addAttribute("name", user.getName());

        return "Admin/AdminHomePage";
    }
    //点击在线页面
    @GetMapping("/loc")
    public String adminLocation(Principal principal,Model model) {

        List<UserDTO> users = userService.findAllByRole("USER");
        User user =userService.findByUsername(principal.getName());
        List<Integer> onlinebv = onlineService.getOnlineBVCount();
        List<Integer> onlinev = helpService.getCountByVid();
        List<Feedback> feedack = feedbackService.getfeedback1();
        List<Feedback> feedack2 = feedbackService.getfeedback2();


        model.addAttribute("users", users);
        model.addAttribute("name", user.getName());
        //在线总人数
        model.addAttribute("onlinesum",onlineService.getCountByStatus());
        model.addAttribute("sum", userService.getCount());
        //在线志愿者人数和盲人数
        model.addAttribute("onlineb", onlinebv.get(0));
        model.addAttribute("onlinev", onlinebv.get(1));
        //等待处理的求助
        model.addAttribute("waiting", onlinev.get(1));
        model.addAttribute("done", onlinev.get(2));
        model.addAttribute("over", onlinev.get(0));
        //待处理的反馈信息
        model.addAttribute("feedback",feedack);
        model.addAttribute("feedback2",feedack2);//建议




        return "Info/LocationInfo";
    }


    @GetMapping("/act")
    public String activities(Principal principal, Model model){
        return "Info/ActivityInfo";
    }

    @GetMapping("/dashboard/backinfodone")
    public String doneBackinfo(@RequestParam int id){
        feedbackService.done(id);
        return "redirect:/loc";
    }


    @PostMapping("/dashboard/delete")
    public String removeUser(@RequestParam int id) {
        //删user表格
        userService.deleteUserById(id);
        //删location表格
        locationService.deleteLocationById(id);
        //删online表格
        onlineService.deleteOnlineById(id);
        //删relation表格
        return "redirect:/dashboard/search2?name=1";
    }

//    @GetMapping("/dashboard/updateUser")
//    public String showUpdateForm(@RequestParam int id , Model model) {
//        UserDTO userDTO= userService.findById(id);
//        model.addAttribute("user",userDTO);
//        return "Admin/UpdateUser";
//    }

//    @PostMapping("/dashboard/updateUser/save")
//    public String updateUser(@ModelAttribute("user") UserDTO userDTO) {
//        userService.updateUser(userDTO);
//        return "redirect:/dashboard";
//    }

    @GetMapping("/dashboard/search")
    public String searchUser(@RequestParam String name ,Principal principal , Model model) {
        List<UserDTO> users = userService.searchUser("USER",name);
        User user =userService.findByUsername(principal.getName());
        model.addAttribute("users",users);
        model.addAttribute("name", user.getName());
        return "Info/UserInfo";
    }

    @GetMapping("/dashboard/search2")
    public String searchUser2(@RequestParam String name,
                             @RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "6") int size,
                             Model model) {
        Pageable pageable = PageRequest.of(page - 1, size); // Spring Data JPA 的分页参数从0开始
        Page<User> users = userService.searchUser2("USER", name, pageable);

//        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        userService.findByUsername(userDetails.getUsername());

        model.addAttribute("users", users.getContent());
        model.addAttribute("name1", name);
        model.addAttribute("totalPages", users.getTotalPages());
        model.addAttribute("totalElements", users.getTotalElements());
        model.addAttribute("presentPage", page);

        System.out.println("Total Pages: " + users.getTotalPages());
        System.out.println("Total Elements: " + users.getTotalElements());
//        System.out.println("Total Pages: " + users.getContent());
        return "Info/UserInfo";
    }

//    查所有盲人
    @GetMapping("/blind")
    public String findBlind(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "6") int size,
            Model model)
    {
        Pageable pageable = PageRequest.of(page - 1, size); // Spring Data JPA 的分页参数从0开始
        Page<User> blinds = userService.searchBlinds(pageable);


        List<User> blindsList = blinds.getContent();
        List<BlindInfo> blindInfos = new ArrayList<>();
        for(User user: blindsList){
            BlindInfo blindInfo = new BlindInfo();
            Relation relation = relationService.findAllByBid(user.getId());
            if(relation == null)
                blindInfo.setGuardianId(null);
            else {
                blindInfo.setGuardianId(relation.getGuardianid());
            }

            blindInfo.setId(user.getId());
            blindInfo.setName(user.getName());
            blindInfo.setUsername(user.getUsername());
            blindInfos.add(blindInfo);

        }

        model.addAttribute("users", blindInfos);
        model.addAttribute("totalPages", blinds.getTotalPages());
        model.addAttribute("totalElements", blinds.getTotalElements());
        model.addAttribute("presentPage", page);

        System.out.println("Total Pages: " + blinds.getTotalPages());
        System.out.println("Total Elements: " + blinds.getTotalElements());
//        System.out.println("Total Pages: " + users.getContent());
        return "Info/BlindInfo";
    }

    //查所有志愿者
    @GetMapping("/volunteer")
    public String findVolunteer(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "6") int size,
            Model model)
    {
        Pageable pageable = PageRequest.of(page - 1, size); // Spring Data JPA 的分页参数从0开始
        Page<User> blinds = userService.searchVolunterrs(pageable);

//        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        User user = userService.findByUsername(userDetails.getUsername());

        model.addAttribute("users", blinds.getContent());
        model.addAttribute("totalPages", blinds.getTotalPages());
        model.addAttribute("totalElements", blinds.getTotalElements());
        model.addAttribute("presentPage", page);

        System.out.println("Total Pages: " + blinds.getTotalPages());
        System.out.println("Total Elements: " + blinds.getTotalElements());
//        System.out.println("Total Pages: " + users.getContent());
        return "Info/VolunteerInfo";
    }
    //查所有亲属
    @GetMapping("/guardian")
    public String findGuardian(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "6") int size,
            Model model)
    {
        Pageable pageable = PageRequest.of(page - 1, size); // Spring Data JPA 的分页参数从0开始
        Page<User> guardians = userService.searchGuardians(pageable);

        List<User> guardiansList = guardians.getContent();
        List<GuardianInfo> guardianInfos = new ArrayList<>();
        for(User user: guardiansList){
            GuardianInfo guardianInfo = new GuardianInfo();
            Relation relation = relationService.findAllByGid(user.getId());
            if(relation == null)
                guardianInfo.blindId=null;
            else {
                guardianInfo.setBlindId(relation.getBlindid());
            }

            guardianInfo.setId(user.getId());
            guardianInfo.setName(user.getName());
            guardianInfo.setUsername(user.getUsername());
            guardianInfos.add(guardianInfo);

        }


        model.addAttribute("users", guardianInfos);
        model.addAttribute("totalPages", guardians.getTotalPages());
        model.addAttribute("totalElements", guardians.getTotalElements());
        model.addAttribute("presentPage", page);

        System.out.println("Total Pages: " + guardians.getTotalPages());
        System.out.println("Total Elements: " + guardians.getTotalElements());
//        System.out.println("Total Pages: " + users.getContent());
        return "Info/GuardianInfo";
    }



    @GetMapping("/dashboard/showroutes")
    @ResponseBody // 这个注解非常重要，它告诉 Spring MVC 返回的是数据而非视图
    public String getRouteById(@RequestParam("id") int id) {
        List<Route> routes = routeService.findByBlindID(id);
        if (!routes.isEmpty()) {
            return routes.get(0).getGeojson(); // 假设你只返回一个 Route 对象
        }
        // 如果没有找到任何路线，你可以抛出异常或者返回 null
        return null;
    }
    //统计各角色人数
    @GetMapping("/dashboard/statis")
    @ResponseBody // 这个注解非常重要，它告诉 Spring MVC 返回的是数据而非视图
    public List<Integer> getStatisByRole() {
        List<Integer> sum = new java.util.ArrayList<>(List.of());
        sum.add(userService.countByUserrole("volunteer"));
        sum.add(userService.countByUserrole("blind"));
        sum.add(userService.countByUserrole("guardian"));
        return sum;
    }

    //超时求助和按时完成的求助
    @GetMapping("/dashboard/help")
    @ResponseBody
    public List<Integer> getHelpByVolunteer() {
        List<Integer> sum = new java.util.ArrayList<>(List.of());
        Timestamp now = new Timestamp(System.currentTimeMillis());
        Timestamp startTime = new Timestamp(now.getTime() - 24 * 60 * 60 * 1000L);

        sum.add(helpService.dayDoneHelp(startTime));//24小时内完成的帮助
        sum.add(helpService.dayOverHelp(startTime));//24小时超时帮助

        return sum;
    }
    //绑定盲人数与未绑定数
    @GetMapping("/dashboard/blindnumber")
    @ResponseBody
    public List<Integer> bindBlind() {
        int b = userService.countByUserrole("blind");
        int r = relationService.count();
        List<Integer> sum = new java.util.ArrayList<>(List.of());
        sum.add(b-r);//未绑定
        sum.add(r);//绑定
        return sum;
    }
    //查询在线人数,好像没用到
    @GetMapping("/dashboard/onlinecount")
    @ResponseBody
    public Integer onlineCount() {

        return onlineService.getCountByStatus();

    }

    //查询离线、等待帮助、帮助中、在线的b人数
    //查询离线、等待帮助、帮助中、在线的v人数
    //offb,offv,helpingb,helpingv,waitingb,onlinev
    @GetMapping("dashboard/onlinebvcount")
    @ResponseBody
    public List<Integer> onlineBlindCount() {
        return onlineService.getOnlineBV();
    }
    //获取所有在线点
    @GetMapping("/points")
    @ResponseBody
    public List<Map<String, Object>> getLocations() {
        return userService.getUserLocations();
    }



    @GetMapping("/dashboard/addUser")
    public String showRegistrationForm(Model model) {
        UserDTO user = new UserDTO();
        model.addAttribute("newUser",user);
        return "User/RegistrationPage";
    }

    @GetMapping("/dashboard/UserInfo")
    public String showUserInfo() {
        return "Info/UserInfo";
    }

    @GetMapping("/dashboard/editProfile")
    public String updateAdminForm(Principal principal, Model model) {

        User user =userService.findByUsername(principal.getName());
        model.addAttribute("user",user);
        return "Admin/UpdateUser";
    }


    @PostMapping("/dashboard/editProfile/save")
    public String updateAdmin(@ModelAttribute("user") UserDTO userDTO) {
        userService.updateUser(userDTO);
        return "redirect:/dashboard";
    }

    @Getter
    @Setter
    public class BlindInfo{
        private int id;
        private String name;
        private String username;
        private Integer guardianId;
    }

    @Getter
    @Setter
    public class GuardianInfo{
        private int id;
        private String name;
        private String username;
        private Integer blindId;
    }




}
